package util

import com.itextpdf.text.Document
import com.itextpdf.text.pdf._
import java.io._

object PdfConcatenator {

  def concatenatePage(pdfCopy: PdfCopy, reader: PdfReader) {
    pdfCopy.addPage(pdfCopy.getImportedPage(reader, 1));
    pdfCopy.freeReader(reader);
  }

  def concatenate(tempFiles: List[File], outputFile: File) {
    val document = new Document();
    val pdfCopy = new PdfCopy(document, new BufferedOutputStream(new FileOutputStream(outputFile)));
    document.open()
    tempFiles.foreach(file => concatenatePage(pdfCopy, new PdfReader(file.getAbsolutePath())))
    document.close()
    tempFiles.foreach(_.delete())
  }
}